package profiles;

import java.text.NumberFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import reports.DetailReport;
import server.Initialize;
import server.db.StmtHelper;
import server.json.FunctionalJSON;
import server.objects.Photo;

import ajaxmethods.SessionMethod;

public class UserProfile extends SessionMethod {

	@Override
	public void perform(HttpServletRequest request,HttpServletResponse response)
	{
		super.perform(request, response);
		StringBuffer sb = new StringBuffer();	
		String userprofile = request.getParameter("userProfile");
		JSONArray listings;
		try {
			
			
			//TODO: Get the actual agents listings
			listings = FunctionalJSON.mapToJSONArray.f(StmtHelper.db("select zillowID,price,useCode,finishedSQFT,bathrooms,bedrooms, (select concat(street,' ',city,', ',state,' ',zip))  as ADDRESS,"+
					" ifnull((select image_url from photos where photos.zillowID=alllist.zillowID and photos.photo_num=1),'"+Photo.getNoPhotoURL()+"') IMGURL"+
			" from alllist group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectIntoMaps.unsafeGet());
		sb.append("<div id=\"homeWorkspaceWrapper\"><div id=\"homeWorkspace\">");
		
		
		JSONObject agent = this.getAgent(userprofile);
		
		sb.append("<div id=\"shortSections\"><h2 style=\"margin:0px;\" class=\"fullname\">"+agent.get("fullname")+"</h4>");
		sb.append("<div id=\"photo\"><img class=\"listViewImage\" src=\""+Initialize.appURL()+"/"+agent.get("image_url")+"\"></div>");
		sb.append("<div class=\"agentfields\">");
		sb.append("<div>"+agent.get("officename")+" - "+agent.get("officeaddress")+"</div><div>"+agent.get("officephone")+"</div></div></div>");
		
		sb.append("<div class=\"relative\"><div class=\"viewtabs\"><div class=\"tab selected\">");
		sb.append("<a class=\"mylistings\" onclick=\"toggleListView(this)\">My Listings</a></div><div class=\"tab\">");
		sb.append("<a class=\"contactme\" onclick=\"toggleListView(this)\">Contact Me</a></div></div></div>");
		
		
		sb.append("<div class=\"scrollable\">");
		sb.append("<div id=\"contactform\" style=\"display:none;\">");
		sb.append("<div class=\"floatInputWrapper\" >" +
				"<p class=\"textbox halfleft\">"+
			    "<label for=\"firstname\">First Name</label>"+
			    "<input type=\"text\" id=\"firstname\" class=\"esoinput\" name=\"firstname\" value=\"\" title=\"firstname\" tabindex=\"1\">"+
			    "<p class=\"textbox halfright\">"+
			    "<label for=\"lastname\">Last Name</label>"+
			    "<input type=\"text\" id=\"lastname\" class=\"esoinput\" name=\"lastname\" value=\"\" title=\"lastname\" tabindex=\"2\">"+
			    "<div id=\"email\"><p class=\"textbox\">"+
			    "<label for=\"email\">Email</label>"+
			    "<input type=\"text\" class=\"esoinput\" name=\"email\" value=\"\" title=\"username\" tabindex=\"4\">"+
			    "</p><div class=\"errorText\">&nbsp;</div></div>" +
			    "<div id=\"message\"><p class=\"textbox\">"+
			    "<label for=\"message\">Leave Me A Message</label>"+
			    "<textarea type=\"text\" class=\"esoinput\" name=\"email\" value=\"\" title=\"message\"></textarea>" +
			    "</p><div class=\"errorText\">&nbsp;</div></div>" +
			    "</div><button class=\"esobutton\" id=\"submitlead\" onclick=\"submitLead()\" title=\"send\" type=\"submit\">Send</button>");
		sb.append("</div>");
		
		sb.append("<div class=\"items\">");
		for(int i = 0; i < listings.length(); i ++)
		{
			JSONObject listing = ((JSONObject)listings.get(i));
			String typ = (String)listing.get("useCode");
			String address =  (String)listing.get("ADDRESS");
			String beds = (String)listing.get("bedrooms");
			String sqft =(String)listing.get("finishedSQFT");
			String primaryphoto = (String)listing.get("IMGURL");
			String bathrooms =(String)listing.get("bathrooms");
			String zillowID = (String)listing.get("zillowID");
			
			String price = NumberFormat.getCurrencyInstance().format(Integer.parseInt((String)listing.get("price")));
			sb.append("<div class=\"mediumReport\">");
			sb.append("<div class=\"content\" style=\"position: relative;margin-left:6px;width: 886px;height: 380px;\"><div id=\"photo\"><div class=\"medphotosize\">" +
					"<a id=\""+zillowID+"\" class=\"fancyphotoLink\" title=\""+address+"\"><img style=\"height: 300px;margin-top: 10px;\" src=\""+primaryphoto+"\"></a></div></div>");
			
			sb.append("<div id=\"propertyBrief\">");
			//TODO:Add Price Field
			sb.append("");
			sb.append("<h3 class=\"propaddress\">"+address+"</h3>");
			sb.append("<div class=\"price\"><span class=\"label\">Price:</span>"+price+"</div>");
			sb.append("<div class=\"beds\"><span class=\"label\">Bedrooms:</span>"+beds+"</div>");
			sb.append("<div class=\"baths\"><span class=\"label\">Bathrooms:</span>"+bathrooms+"</div>");
			sb.append("<div class=\"proptype\"><span class=\"label\">Property Type:</span>"+typ+"</div>");
			sb.append("<div class=\"sqft\"><span class=\"label\">Square Feet:</span>"+sqft+"</div>");
			sb.append("<div class=\"linkWrapper\"><div id=\"detailview\"><a id=\""+zillowID+"\" title=\""+address+"\" class=\"detailLink moredetails\">More Details</a></div></div>");
			sb.append("</div>");
			sb.append("</div></div>");
		}
		sb.append("</div></div>");
		sb.append("<div class=\"action\"><div class=\"insideAction\"><a class=\"prev\" >&#x25C0; Prev</a><a class=\"next\">Next &#x25BA;</a></div></div>");
		sb.append(javaScriptOut());
			
		data.put("HOME", sb.toString()).write(response.getWriter());

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	public static JSONObject getAgent(String contextpath) {
		try {
			return FunctionalJSON.mapToJSONObject.f(StmtHelper.db("select idagents,image_url,fullname,contextpath,agentid,directline,officephone,mobile,fax,officename,officeaddress,emailaddress from agents where contextpath=").addVariable(contextpath)
				.collectIntoMaps.unsafeGet());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public StringBuffer javaScriptOut() {
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		sb.append("$('.fancyphotoLink').click(function(){var link = $(this); if(link.find('img').attr('src').indexOf('nophotoavail')==-1)$.post('"+Initialize.appURL()+"/ajaxCall.jsp?do=reports.Photos',{zillowID:link.attr('id')},function(data, textStatus, XMLHttpRequest) {"+
		"	if(data){$.fancybox(data,{title:link.attr('title'),type:'image', transitionIn:'elastic',transitionOut:'elastic',easingIn:'easeOutBack',easingOut:'easeInBack',width:500});}});}); ");
		sb.append("function toggleListView(elem) {\n" +
				"if(!$(elem).parent().hasClass('selected'))\n" +
				"{"+
				"	$('.viewtabs .tab').each(function(){if($(this).hasClass('selected')) $(this).removeClass('selected'); else $(this).addClass('selected'); });\n" +
				"if($(elem).hasClass('contactme'))" +
				"	$('#homeWorkspace .action').fadeOut(function(){$('.scrollable .items').fadeOut(function(){$('#contactform').fadeIn();});});" +
				"else if($(elem).hasClass('mylistings'))" +
				"	$('#contactform').fadeOut(function(){$('#homeWorkspace .action,.scrollable .items').fadeIn();});" +
				"}" +
				"}");
		sb.append(DetailReport.javaScriptOut());
		sb.append("</script>");
		return sb;
	}

}
